package controller;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pojo.Page;
import pojo.Supplier;
import service.SupplierService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;


@Controller
@RequestMapping("/supplier")
public class SupplierController extends BaseController{
    Logger logger=Logger.getLogger(SupplierController.class);
    @Resource
    private SupplierService supplierService;
    @GetMapping("/list")
    public String getSupplierList(Model model, String querySupCode, String querySupName, @RequestParam(defaultValue = "1")Integer pageIndex){
        List<Supplier> supplierList=null;
        try {
            Page page=new Page();
            page.setPageSize(5);
            page.setCurPage(pageIndex);
            supplierList=supplierService.select(querySupCode,querySupName,page);
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("querySupCode",querySupCode);
            model.addAttribute("querySupName",querySupName);
            model.addAttribute("totalPageCount",page.getTotalPage());
            model.addAttribute("totalCount",page.getTotalCount());
            model.addAttribute("currentPageNo",page.getCurPage());
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/toSysError";
        }
        return "supplier/list";
    }

    @GetMapping("/toAdd")
    public String toAdd(@ModelAttribute("supplier") Supplier supplier){
        return "supplier/add";
    }
//     上机04
//    @PostMapping("/add")
//    public String add(@ModelAttribute("supplier")@Valid Supplier supplier, BindingResult bindingResult,Model model){
//        if (bindingResult.hasErrors()){
//            return "supplier/add";
//        }
//        if (supplierService.add(supplier)>0){
//            model.addAttribute("supplier",supplier);
//            return "redirect:/supplier/list";
//        }
//        return "supplier/add";
//    }
    @PostMapping("/add")
    public String add(@Valid Supplier supplier, HttpServletRequest request, @RequestParam(value = "pics",required = false)MultipartFile[]pics){
         String companyLicPicPath=null;
         String orgCodePicPath=null;
         String errorInfo=null;
         boolean flag=true;
         String path=request.getSession().getServletContext().getRealPath("/upload");
         logger.debug("文件存储路径:"+path);
         for (int i=0;i<pics.length;i++){
             MultipartFile pic=pics[i];
             if (!pic.isEmpty()){
                 if (i==0){
                     errorInfo="uploadFileError1";
                 }else if (i==1){
                     errorInfo="uploadFileError2";
                 }
                 String oldFileName=pic.getOriginalFilename();  //原文件名
                 logger.debug("原文件名:"+oldFileName);
                 String prefix= FilenameUtils.getExtension(oldFileName);   //原文件后缀
                 logger.debug("原文件后缀:"+prefix);
                 int fileSize=8000000;
                 if (pic.getSize()>fileSize){
                     request.setAttribute(errorInfo,"*上传大小不得超过8MB");
                 }else if (prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("gif")){
                     String fileName= UUID.randomUUID()+"."+prefix; //新的文件名
                     logger.debug("新的文件名："+fileName);
                     File targetFile=new File(path);
                     if(!targetFile.exists()){
                         targetFile.mkdirs();
                     }
                     try{
                         pic.transferTo(new File(targetFile,fileName));
                     }catch (Exception e){
                         e.printStackTrace();
                         request.setAttribute(errorInfo,"上传失败！");
                         flag=false;
                     }
                     if (i==0){
                         companyLicPicPath="/upload"+File.separator+fileName;
                     }else if (i==1){
                         orgCodePicPath="/upload"+File.separator+fileName;
                     }
                     logger.debug(companyLicPicPath);
                     logger.debug(orgCodePicPath);
                 }else {
                     request.setAttribute(errorInfo,"文件格式不正确");
                     flag=false;
                 }
             }
         }
         if (flag){
             supplier.setCompanyLicPicPath(companyLicPicPath);
             supplier.setOrgCodePicPath(orgCodePicPath);
             if (supplierService.add(supplier)>0){
                 return "redirect:/supplier/list";
             }
         }
         return "supplier/add";
    }
    @GetMapping("/view/{proid}")
    public String view(@PathVariable String proid,Model model){
        Supplier supplier=supplierService.getSupplierById(proid);
        model.addAttribute("supplier",supplier);
        return "supplier/view";
    }
    @GetMapping("toUpdate")
    public String toUpdate(@RequestParam String supplierId,Model model){
        Supplier supplier=supplierService.getSupplierById(supplierId);
        model.addAttribute("supplier",supplier);
        return "supplier/update";
    }
    @PostMapping("/update")
    public String update(Supplier supplier){
        if (supplierService.updateSupplier(supplier)>0){
            return "redirect:/supplier/list";
        }
        return "supplier/update";
    }
    @ResponseBody
    @GetMapping("/deleteById")
    public Object deleteById(@RequestParam String proid){
        HashMap<String,Object> hashMap=new HashMap<String, Object>();
        if (supplierService.del(proid)>0){
            hashMap.put("delResult","true");
        }else {
            hashMap.put("delResult","false");
        }
        return hashMap;
    }


}
